package com.demo.netty;

import org.jboss.netty.channel.*;

import java.io.IOException;
import java.util.Scanner;

public class ServerHandler extends SimpleChannelUpstreamHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        Channel channel = e.getChannel();
        MessageType message = (MessageType) e.getMessage();
        System.out.println("server >");
        switch (message.getType()) {
            case MessageType.ONE:
                System.out.println("receive a message: " + message.getContext()+" MessageType is "+MessageType.ONE);
                MessageType messageType = new MessageType();
                messageType.setType(2);
                messageType.setContext("i am server i send you a message: hi client");
                channel.write(messageType);
                break;
            case MessageType.TWO:
                channel.close();
                System.out.println("receive a message: " + message.getContext()+" MessageType is "+MessageType.TWO);
                break;
            case MessageType.THREE:
                System.out.println("receive a message: " + message.getContext()+" MessageType is "+MessageType.THREE);
                break;
            default:
                throw new IOException("unknown type message " + message.getType());
        }
        System.out.println("向client发送消息：> ");
        Scanner scanner = new Scanner(System.in);
        MessageType messageType = new MessageType();
        String next = scanner.next().trim();
        String[] split = next.split(",");
        messageType.setType(Integer.parseInt(split[0]));
        messageType.setContext(split[1]);
        channel.write(messageType);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        System.out.println("server exceptionCaught");
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("server channelConnected");
        super.channelConnected(ctx, e);
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("server channelDisconnected");
        super.channelDisconnected(ctx, e);
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("server channelClosed");
        super.channelClosed(ctx, e);
    }
}
